package co.fitstart.market.web.controller.jinjiamedia;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.entity.user.User;
import co.fitstart.market.handler.JinjiaHandler;
import co.fitstart.market.service.UserService;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("")
public class JinjiaMediaController {
	
	private static final Logger logger = LoggerFactory.getLogger(JinjiaMediaController.class);
	
	@Autowired
	private JinjiaHandler jinjiaHandler;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 
	 * @param serailNumber
	 * @return
	 */
	@RequestMapping(value = "/jinjiamedia/registe", method = RequestMethod.GET)
	public ModelAndView registe(@RequestParam("serailNumber") String serailNumber) {
		
		ModelAndView modelAndView = new ModelAndView("/jinjiamedia/registe");
		modelAndView.addObject("serailNumber", serailNumber);
		
		return modelAndView;
	}
	
	/**
	 * 
	 * @param userName
	 * @param mobile
	 * @param serailNumber
	 * @return
	 */
	@RequestMapping(value = "/jinjiamedia/registe", method = RequestMethod.POST)
    public @ResponseBody String onRegiste(@RequestParam("userName") String userName,
    									  @RequestParam("mobile") String mobile,
    									  @RequestParam("serailNumber") String serailNumber) {
		Result result = new Result();
		
		try {
			
			User old = userService.getUser(mobile);
			
			if(old != null) {
				result.fail().message("用户已认领");
				return JsonUtils.toJsonString(result);
			}
			
			User user = new User(mobile, userName, false, "jinjiamedia");
			userService.save(user);
			result = jinjiaHandler.onRegiste(serailNumber, userName, user.getId(), "SUCCESS");
			
			if(!result.isValid()) {
				return JsonUtils.toJsonString(result);
			} 
			
			result.success().message("认领成功");
			return JsonUtils.toJsonString(result);
			
		} catch (Exception e) {
			
			logger.error("onRegiste occurs error", e);
			result.fail().message("认领错误");
			return JsonUtils.toJsonString(result);
		}
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/jinjiamedia/result", method = RequestMethod.GET)
	public ModelAndView result() {
		ModelAndView modelAndView = new ModelAndView("/jinjiamedia/result");
		
		return modelAndView;
	}
			
}
